<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item prop="orgName">
        <el-input
          v-model="queryParams.orgName"
          placeholder="请输入机构名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="switchState">
        <el-select v-model="queryParams.switchState" placeholder="开关状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_switch_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="auditState">
        <el-select v-model="queryParams.auditState" placeholder="请选择审核状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_audit_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:org:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleUpdate"
          v-hasPermi="['system:org:edit']"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleAudit"
          v-hasPermi="['system:org:audit']"
          >审核
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleUnaudit"
          v-hasPermi="['system:org:audit']"
          >反审核
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['system:org:delete']"
          >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:org:export']"
          >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠 </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="orgList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="机构名称" prop="orgName"></el-table-column>
      <el-table-column label="联系人" prop="contacts" width="80" />
      <el-table-column label="联系电话" prop="telephone" width="120" />
      <el-table-column label="联系邮箱" prop="email" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="150" />
      <el-table-column prop="switchState" label="开关状态" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_switch_status" :value="scope.row.switchState" />
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditState" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_audit_status" :value="scope.row.auditState" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:org:edit']"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAudit(scope.row)"
            v-hasPermi="['system:org:audit']"
            >审核
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUnaudit(scope.row)"
            v-hasPermi="['system:org:audit']"
            >反审核
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:org:delete']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改机构信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="15" v-if="form.parentId !== 0">
            <el-form-item label="上级机构" prop="parentId">
              <treeselect
                v-model="form.parentId"
                :options="orgOptions"
                :normalizer="normalizer"
                placeholder="选择上级机构"
                @select="handleSelectParent"
              />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="插入位置" prop="insertPosition">
              <el-select v-model="form.insertPosition" placeholder="选择插入位置">
                <el-option
                  v-for="dict in dict.type.sys_insert_position"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  :disabled="rootDisabled(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="机构名称" prop="orgName">
              <el-input v-model="form.orgName" placeholder="请输入机构名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contacts">
              <el-input v-model="form.contacts" placeholder="请输入联系人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="telephone">
              <el-input v-model="form.telephone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入联系邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构状态">
              <el-radio-group v-model="form.switchState">
                <el-radio v-for="dict in dict.type.sys_switch_status" :key="dict.value" :label="dict.value"
                  >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrg,
  getOrg,
  delOrg,
  addOrg,
  updateOrg,
  queryRelease,
  queryRecycle,
  auditByIds,
  unauditByIds,
  recoverByIds,
  removeByIds,
} from '@/api/system/org';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

export default {
  name: 'Org',
  dicts: ['sys_delete_status', 'sys_audit_status', 'sys_switch_status', 'sys_insert_position'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      orgList: [],
      // 机构树选项
      orgOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        parentId: null,
        parentCode: null,
        orgName: null,
        level: null,
        subnum: null,
        contacts: null,
        telephone: null,
        email: null,
        auditState: null,
        editState: null,
        switchState: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [{ required: true, message: '上级机构不能为空', trigger: 'blur' }],
        orgName: [{ required: true, message: '机构名称不能为空', trigger: 'blur' }],
        email: [
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change'],
          },
        ],
        telephone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询机构信息列表 */
    getList() {
      this.loading = true;
      listOrg(this.queryParams).then((resultDTO) => {
        this.orgList = this.handleTree(resultDTO.data?.list, 'id');
        console.log(resultDTO);
        this.loading = false;
      });
    },
    /** 转换机构数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.orgName,
        children: node.children,
        isDisabled: node.switchState === 1,
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    rootDisabled(value) {
      const parent = this.form.parent;
      if (parent && (value === 'after' || value === 'before')) {
        console.log(parent.lvalue, parent.rvalue, this.form.lvalue, this.form.rvalue, value);
        if (parent.id == '1') {
          return true;
        }
        if (value === 'after') {
          if (parent.rvalue - 1 == this.form.rvalue) {
            return true;
          }
        } else {
          if (parent.lvalue + 1 == this.form.lvalue) {
            return true;
          }
        }
      }
      return false;
    },
    handleSelectParent(item) {
      this.form.parent = item;
      if (item.id === '1') {
        console.log(item);
        this.form.insertPosition = 'first_child';
      }
      if (!this.form.insertPosition) {
        this.form.insertPosition = 'first_child';
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        ancestors: null,
        parentCode: null,
        orgName: null,
        insertPosition: 'first_child',
        lvalue: null,
        rvalue: null,
        level: null,
        subnum: null,
        contacts: null,
        telephone: null,
        email: null,
        auditState: 0,
        deleted: 0,
        editState: 0,
        switchState: 0,
        updateTime: null,
        updateBy: null,
        createTime: null,
        createBy: null,
        auditTime: null,
        auditBy: null,
        remark: null,
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.id;
      }
      this.open = true;
      this.title = '添加部门信息';
      queryRelease().then((resultDTO) => {
        this.orgOptions = this.handleTree(resultDTO.data?.list, 'id');
        console.log(this.orgOptions);
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getOrg(id).then((resultDTO) => {
        this.form = resultDTO.data;
        this.open = true;
        this.title = '修改部门信息';
      });
      // listOrgExcludeChild(row.id).then(resultDTO => {
      //   this.orgOptions = this.handleTree(resultDTO.data?.list, "id");
      // });
      queryRelease().then((resultDTO) => {
        this.orgOptions = this.handleTree(resultDTO.data?.list, 'id');
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateOrg(this.form).then((resultDTO) => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addOrg(this.form).then((resultDTO) => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否审核部门信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return auditByIds(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('审核成功');
        })
        .catch(() => {});
    },
    /** 反审核按钮操作 */
    handleUnaudit(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否反审核部门信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return unauditByIds(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('反审核成功');
        })
        .catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除部门编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOrg(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 逻辑删除按钮操作 */
    handleRemove(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认逻辑删除部门信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return removeByIds(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 还原删除按钮操作 */
    handleRecover(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认还原删除部门信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return recoverByIds(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('还原成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/org/export',
        {
          ...this.queryParams,
        },
        `org_${new Date().getTime()}.xlsx`,
      );
    },
  },
};
</script>
